package com.hongdee.rbac.oil.service.impl;
import com.hongdee.common.util.EntityUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.rbac.oil.dao.ITBcOilDao;
import com.hongdee.rbac.oil.entity.TBcOilEntity;
import com.hongdee.rbac.oil.service.ITBcOilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Liu XiaoLong
 * Date: 2018/1/22.
 * Remark:
 */
@Service
public class TBcOilServiceImpl implements ITBcOilService {

    @Autowired
    private ITBcOilDao itBcOilDao;
    private String tableName = "T_BC_OIL";

    @Override
    public Map add(TBcOilEntity tBcOilEntity,String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        tBcOilEntity.setConpanyId(companyId);
        EntityUtils.valid(tBcOilEntity);
        String id = tBcOilEntity.getId();
        if(id == null) {
            id = "";
        }
        if(id.equals("")){ // 新增操作
            //tBcOilEntity.setId(StringUtil.UUID()); // 添加ID主键

            if(tBcOilEntity.getLevel().equals("0")){ // 资源树0层
               itBcOilDao.saveOrUpdate(tBcOilEntity);
            }
            if(tBcOilEntity.getLevel().equals("1")){ // 资源树1层
                if(isExisting(1,"","",tBcOilEntity.getOilBrand(),companyId) == true){ // 判断是否已经存在
                    throw new Exception("机油品牌名称重复，添加失败");
                }
                itBcOilDao.saveOrUpdate(tBcOilEntity);
            }
            if(tBcOilEntity.getLevel().equals("2")){ // 资源树2层
                if(isExisting(2,tBcOilEntity.getpId(),"",tBcOilEntity.getOilName(),companyId) == true){// 判断是否已经存在
                    throw new Exception("机油名称重复，添加失败");
                }
                itBcOilDao.saveOrUpdate(tBcOilEntity);
            }
        }
        else { // 更新操作
            if(tBcOilEntity.getLevel().equals("0")){ // 资源树0层
                itBcOilDao.saveOrUpdate(tBcOilEntity);
            }
            if(tBcOilEntity.getLevel().equals("1")){ // 资源树1层
                if(isExisting(3,"",tBcOilEntity.getId(),tBcOilEntity.getOilBrand(),companyId) == true){ // 判断是否已经存在
                    throw new Exception("机油品牌名称重复，添加失败");
                }
                itBcOilDao.saveOrUpdate(tBcOilEntity);
            }
            if(tBcOilEntity.getLevel().equals("2")){ // 资源树2层
                if(isExisting(4,tBcOilEntity.getpId(),tBcOilEntity.getId(),tBcOilEntity.getOilName(),companyId) == true){// 判断是否已经存在
                    throw new Exception("机油名称重复，添加失败");
                }
                itBcOilDao.saveOrUpdate(tBcOilEntity);
            }
        }
        Map map = new HashMap();
        map.put("success",true);
        return map;
    }

    @Override
    public Map delete() throws Exception {
        return null;
    }
/**
 * @Name: 获取单条信息
 * @Author: Liu XiaoLong
 * @Date: 2018/1/23 17:15
 * @Remark:
 */
    @Override
    public Map Info(String uid,String id) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        String sql = "select * from "+tableName+" where id = ? ";

        Map map = new HashMap();
        map.put("data",itBcOilDao.info(sql,id));
        return map;
    }

    /**
     * @Name: 分页查询
     * @Author: Liu XiaoLong
     * @Date: 2018/1/22 17:08
     * @Remark:
     */
    @Override
    public Map page(String uid,String start,String limit,String level,String pId) throws Exception {
        String sql = "select * from "+tableName+" where company_id = ? ";
        List list = new ArrayList();
        list.add(TokenUtil.getCompanyId(uid));

        if(level.equals("0")){ // 查询树0层
            sql += "and level = ? ";
            list.add(level);
        }else { // 非0层
            sql += "and level = ? and p_id = ? ";
            list.add(level);
            list.add(pId);
        }

        return itBcOilDao.page(sql,list.toArray(),start,limit);
    }

    /**
     * @Name: 获取资源树
     * @Author: Liu XiaoLong
     * @Date: 2018/1/22 17:54
     * @Remark:
     */
    @Override
    public Map getDataTree(String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        List params0 = new ArrayList();
        String sql0 = "SELECT * FROM t_bc_oil WHERE company_id = ? AND level = 0 ";
        params0.add(companyId);
        List respList0 = itBcOilDao.list(sql0,params0.toArray());
        List returnList = new ArrayList();
        for(int i = 0;i<respList0.size();i++){
            Map map = (Map) respList0.get(i);
            map.put("treeName",map.get("oilBrand").toString());
            hasChild(map,map.get("id").toString(),companyId,1);
            returnList.add(map);
        }
        Map map = new HashMap();
        map.put("dataList",returnList);
        return map;
    }
/**
 * @Name: 删除组或组下的所有数据
 * @Author: Liu XiaoLong
 * @Date: 2018/1/23 19:21
 * @Remark:
 */
    @Override
    public Map deleteGroup(String uid, String id,String level) throws Exception {
        List params = new ArrayList();
        String sql = "";
        if(level.equals("0") || level.equals("1")){
            sql = "DELETE FROM t_bc_oil WHERE id = ? OR p_id = ? ";
            params.add(id);
            params.add(id);
        }else {
            sql = "DELETE FROM t_bc_oil WHERE id = ? ";
            params.add(id);
        }
        itBcOilDao.executeSQL(sql,params.toArray());
        Map map = new HashMap();
        map.put("success",true);
        map.put("msg","删除成功");
        return map;
    }
    /**
     * @Name: 更新组和组下所有数据
     * @Author: Liu XiaoLong
     * @Date: 2018/1/23 21:13
     * @Remark:
     */
    public Map updateGroup(String uid,TBcOilEntity tBcOilEntity) throws Exception {
        List params = new ArrayList();
        String sql = "";
        Map map = new HashMap();
        String companyId = TokenUtil.getCompanyId(uid);
        tBcOilEntity.setConpanyId(companyId);
       //tBcOilEntity.setId( tBcOilEntity.getId() == null ? "":tBcOilEntity.getId());
        String id = tBcOilEntity.getId();
        if(id == null) {
            id = "";
        }
        if(id.equals("")){ // 新增
            if(isExisting(5,tBcOilEntity.getpId(),"",tBcOilEntity.getOilBrand(),companyId) == true){ // 判断是否已经存在
                throw new Exception("机油品牌名称重复，添加失败");
            }

            itBcOilDao.saveOrUpdate(tBcOilEntity);
            map.put("success",true);
            map.put("msg","更新成功");
        }else { // 更新

            if(isExisting(6,tBcOilEntity.getpId(),tBcOilEntity.getId(),tBcOilEntity.getOilBrand(),companyId) == true){ // 判断是否已经存在
                throw new Exception("机油品牌名称重复，更新失败");
            }

            if(tBcOilEntity.getLevel().equals("0") || tBcOilEntity.getLevel().equals("1")){
                sql = "UPDATE t_bc_oil SET oil_brand = ? WHERE id = ? OR p_id = ? ";
                params.add(tBcOilEntity.getOilBrand());
                params.add(tBcOilEntity.getId());
                params.add(tBcOilEntity.getId());
                map.put("success",true);
                map.put("msg","更新成功");
            }else {
                map.put("success",true);
                map.put("msg","更新条数为0");
            }
            itBcOilDao.executeSQL(sql,params.toArray());
        }
        return map;
    }

/**
 * @Name: 有无孩子，有则放到child里，无则不操作
 * @Author: Liu XiaoLong
 * @Date: 2018/1/23 20:59
 * @Remark:
 */
    private void hasChild(Map map,String id,String companyId,int level) throws  Exception {
        String sql = "select * from t_bc_oil where company_id = ? and level = ? and p_id = ? ";
        List params = new ArrayList();
        params.add(companyId);
        params.add(level);
        params.add(id);
        List list = itBcOilDao.list(sql,params.toArray());
        if(list.size()>0){//如果有子类
            map.put("child",list);//把子类放入“child”对象中
            level += 1;
            for(int i = 0;i<list.size();i++){// 遍历子类，看有没有孙类，递归循环。。。。
                Map mapChild = (Map) list.get(i);
                if(level == 2){//根据层级不同，选择参数树显示的参数所对应的字段
                    mapChild.put("treeName",mapChild.get("oilBrand").toString());
                }
                else {
                    mapChild.put("treeName",mapChild.get("oilName").toString());
                }
                // 递归
                hasChild(mapChild, mapChild.get("id").toString(),mapChild.get("companyId").toString(),level);
            }
        }
        else {
            //level -=1;
        }
    }

    /**
     * @Name: 判断数据是否存在
     * @Author: Liu XiaoLong
     * @Date: 2018/1/22 14:38
     * @Remark:
     */
    private boolean isExisting(int type,String pId,String id,String value,String companyId) throws Exception {
        String sql = "SELECT * FROM "+tableName+" WHERE company_id=? ";
        List params = new ArrayList();
        params.add(companyId);

        if(type == 1){ // 查机油品牌
            sql += "AND oil_brand = ? ";
            params.add(value);
        }
        if(type == 2){ // 查机油名称
            sql += "AND oil_name = ? AND p_id = ? ";
            params.add(value);
            params.add(pId);
        }
        if(type == 3){ // 编辑时,查机油品牌(除自己之外无重复数据)
            sql += "AND id <> ? AND oil_brand = ?  ";
            params.add(id);
            params.add(value);
        }
        if(type == 4){ // 编辑时,查机油名称(除自己之外无重复数据)
            sql += "AND id <> ? AND oil_name = ? AND p_id = ? ";
            params.add(id);
            params.add(value);
            params.add(pId);
        }
        if(type == 5){ // 查机油品牌
            sql += "AND oil_brand = ? AND p_id = ? ";
            params.add(value);
            params.add(pId);
        }
        if(type == 6){ // 查机油品牌
            sql += "AND oil_brand = ? AND p_id = ? AND id <> ? ";
            params.add(value);
            params.add(pId);
            params.add(id);
        }
        Map map = itBcOilDao.info(sql,params.toArray());
        if(map.size()>0){ // 已经存在
            return true;
        }else {
            return false;
        }

    }
}
